<template>
  <div class="markdown-body" v-html="renderedContent"></div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import { marked } from "marked";
import hljs from "highlight.js";
import "highlight.js/styles/atom-one-dark.css";
import MarkdownIt from "markdown-it";
import mk from "@traptitech/markdown-it-katex";

const props = defineProps({
  content: {
    type: String,
    default: "",
  },
});

// 配置marked
marked.setOptions({
  gfm: true, // 启用GitHub风格的Markdown
  breaks: true, // 将回车转换为<br>
  highlight: function (code, lang) {
    try {
      if (lang && hljs.getLanguage(lang)) {
        return hljs.highlight(code, { language: lang }).value;
      } else {
        return hljs.highlightAuto(code).value;
      }
    } catch (e) {
      console.error("高亮显示失败:", e);
      return code;
    }
  },
});

// 配置markdown-it（用于更好的表格和KaTeX支持）
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return (
          '<pre class="hljs"><code>' +
          hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
          "</code></pre>"
        );
      } catch (__) {}
    }
    return (
      '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + "</code></pre>"
    );
  },
}).use(mk, { throwOnError: false, errorColor: " #cc0000" });

const renderedContent = computed(() => {
  try {
    // 使用markdown-it渲染内容
    return md.render(props.content || "");
  } catch (e) {
    console.error("Markdown渲染失败:", e);
    // 如果markdown-it失败，回退到marked
    try {
      return marked(props.content || "");
    } catch (e) {
      console.error("Marked渲染也失败:", e);
      return props.content || "";
    }
  }
});

// 处理代码块的复制功能
const setupCodeCopy = () => {
  const codeBlocks = document.querySelectorAll(".markdown-body pre");
  codeBlocks.forEach((block) => {
    if (!block.classList.contains("code-block-wrapper")) {
      // 创建复制按钮
      const copyButton = document.createElement("button");
      copyButton.className = "copy-button";
      copyButton.innerHTML = "复制";
      copyButton.onclick = (e) => {
        e.stopPropagation();
        const code = block.querySelector("code").innerText;
        navigator.clipboard
          .writeText(code)
          .then(() => {
            copyButton.innerHTML = "已复制!";
            setTimeout(() => {
              copyButton.innerHTML = "复制";
            }, 2000);
          })
          .catch((err) => {
            console.error("复制失败:", err);
          });
      };

      // 创建一个包装器包含原代码块和按钮
      const wrapper = document.createElement("div");
      wrapper.className = "code-block-wrapper relative";
      block.parentNode.insertBefore(wrapper, block);
      wrapper.appendChild(block);
      wrapper.appendChild(copyButton);
    }
  });
};

// 当内容变化时，重新设置代码复制功能
watch(
  () => props.content,
  () => {
    setTimeout(setupCodeCopy, 100);
  },
  { immediate: false },
);

onMounted(() => {
  setTimeout(setupCodeCopy, 100);
});
</script>

<style scoped>
.markdown-body {
  color: inherit;
  line-height: 1.6;
}

/* 使用正确的深度选择器语法 */
:deep(.markdown-body) h1,
:deep(.markdown-body) h2,
:deep(.markdown-body) h3,
:deep(.markdown-body) h4,
:deep(.markdown-body) h5,
:deep(.markdown-body) h6 {
  margin-top: 1.5em;
  margin-bottom: 0.5em;
  font-weight: 600;
  line-height: 1.25;
}

:deep(.markdown-body) h1 {
  font-size: 2em;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.3em;
}
:deep(.markdown-body) h2 {
  font-size: 1.5em;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.3em;
}
:deep(.markdown-body) h3 {
  font-size: 1.25em;
}
:deep(.markdown-body) h4 {
  font-size: 1em;
}
:deep(.markdown-body) h5 {
  font-size: 0.875em;
}
:deep(.markdown-body) h6 {
  font-size: 0.85em;
  color: #6a737d;
}

:deep(.markdown-body) p,
:deep(.markdown-body) ul,
:deep(.markdown-body) ol,
:deep(.markdown-body) blockquote,
:deep(.markdown-body) table {
  margin-bottom: 1em;
}

:deep(.markdown-body) a {
  color: #0366d6;
  text-decoration: none;
}

:deep(.markdown-body) a:hover {
  text-decoration: underline;
}

:deep(.markdown-body) strong {
  font-weight: 600;
}

/* 列表 */
:deep(.markdown-body) ul,
:deep(.markdown-body) ol {
  padding-left: 2em;
}

:deep(.markdown-body) li + li {
  margin-top: 0.25em;
}

/* 块引用 */
:deep(.markdown-body) blockquote {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
}

/* 代码 */
:deep(.markdown-body) code {
  padding: 0.2em 0.4em;
  margin: 0;
  font-size: 85%;
  background-color: rgba(27, 31, 35, 0.05);
  border-radius: 3px;
  font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
}

:deep(.markdown-body) pre {
  margin-top: 0;
  margin-bottom: 16px;
  word-wrap: normal;
  padding: 16px;
  overflow: auto;
  font-size: 85%;
  line-height: 1.45;
  background-color: #f6f8fa;
  border-radius: 3px;
}

:deep(.markdown-body) pre code {
  padding: 0;
  margin: 0;
  background-color: transparent;
  border: 0;
  word-break: normal;
  white-space: pre;
}

/* 表格 */
:deep(.markdown-body) table {
  border-collapse: collapse;
  width: 100%;
  overflow: auto;
  display: block;
}

:deep(.markdown-body) table th {
  font-weight: 600;
}

:deep(.markdown-body) table th,
:deep(.markdown-body) table td {
  padding: 6px 13px;
  border: 1px solid #dfe2e5;
}

:deep(.markdown-body) table tr {
  background-color: #fff;
  border-top: 1px solid #c6cbd1;
}

:deep(.markdown-body) table tr:nth-child(2n) {
  background-color: #f6f8fa;
}

/* 图片 */
:deep(.markdown-body) img {
  max-width: 100%;
  box-sizing: content-box;
  background-color: #fff;
}

/* 水平线 */
:deep(.markdown-body) hr {
  height: 0.25em;
  padding: 0;
  margin: 24px 0;
  background-color: #e1e4e8;
  border: 0;
}

/* 代码复制按钮 */
:deep(.markdown-body) .code-block-wrapper {
  position: relative;
}

:deep(.markdown-body) .copy-button {
  position: absolute;
  top: 5px;
  right: 5px;
  padding: 3px 8px;
  font-size: 12px;
  color: #0366d6;
  background-color: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 3px;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s;
}

:deep(.markdown-body) .code-block-wrapper:hover .copy-button {
  opacity: 1;
}

/* 黑暗模式 */
@media (prefers-color-scheme: dark) {
  :deep(.markdown-body) pre,
  :deep(.markdown-body) code {
    background-color: #2d333b;
  }

  :deep(.markdown-body) blockquote {
    border-left-color: #444c56;
    color: #8b949e;
  }

  :deep(.markdown-body) table th,
  :deep(.markdown-body) table td {
    border-color: #373e47;
  }

  :deep(.markdown-body) table tr {
    background-color: transparent;
    border-top-color: #373e47;
  }

  :deep(.markdown-body) table tr:nth-child(2n) {
    background-color: #161b22;
  }

  :deep(.markdown-body) hr {
    background-color: #444c56;
  }

  :deep(.markdown-body) a {
    color: #2f81f7;
  }

  :deep(.markdown-body) .copy-button {
    background-color: #2d333b;
    color: #2f81f7;
    border-color: #444c56;
  }
}
</style>
